package NC54_数组中相加和为0的三元组;

import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (num == null || num.length < 3){
            return res;
        }

        Arrays.sort(num);
        int sum, left, right;

        for (int i = 0; i < num.length - 2; i++){
            if (i != 0 && num[i] == num[i - 1]){
                continue;
            }

            left = i + 1;
            right = num.length - 1;
            while (left < right){
                sum = num[left] + num[right];
                if (sum + num[i] == 0){
                    ArrayList<Integer> list = new ArrayList<>();
                    list.add(num[i]);
                    list.add(num[left]);
                    list.add(num[right]);
                    res.add(list);
                    left++;
                    right--;

                    while (left < right && num[left] == num[left - 1]){
                        left++;
                    }
                    while (left < right && num[right] == num[right + 1]){
                        right--;
                    }

                }else if (sum + num[i] < 0){
                    left++;
                }else {
                    right--;
                }
            }
        }
        return res;
    }
}